<%@ page contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.model.Table"%>
<%@page import="dbexp.model.TableData"%>
<%@page import="dbexp.model.Column"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="dbexp.connection.DbConnection"%>
<%@page import="org.json.JSONObject"%>
<%@page import="org.json.JSONArray"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
String sstart = request.getParameter("start");
String slimit = request.getParameter("limit");
boolean brak = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
Table object =  new Table(name,schema);
JSONObject myout = new JSONObject();
if(!brak){
	int start = 0;
	int limit = 0;
	try{
		start = Integer.parseInt(sstart);
		limit = Integer.parseInt(slimit);
	}catch(Exception e){}
	object = DbMetaData.getTable(u, name.toUpperCase(), schema.toUpperCase());
	String query = "SELECT * FROM "+object.getObjectNameForQuery();
	if(start==0 && limit>0){
		query += " WHERE ROWNUM"+((limit>1)?"<":"")+"="+limit;
	}else{
		if(start>1){
			query = "SELECT LIMITQUERY.* FROM (SELECT ROWNUM AS NR,T.* FROM "+object.getObjectNameForQuery()+" T WHERE ROWNUM<=" +(start+limit)+
					") LIMITQUERY WHERE NR>= "+start;
			if(limit>0){
				query += " AND NR<="+(start+limit);
			}
		}
	}
	TableData tableData = DbMetaData.getData(u,query);
	JSONArray data = new JSONArray();
	long count = DbMetaData.getCount(u,object.getObjectNameForQuery());
	myout.put("total",count);
	
	List<Column> columns = DbMetaData.getColumnsFromQuery(u, query);
	List<List<Object>> rows = tableData.getRows();
	for(int row=0;row<rows.size();row++){
		List<Object> rc = rows.get(row);
		JSONObject record = new JSONObject();
		for (int col=0;col<columns.size();col++) {
			Column column = (Column) columns.get(col);
			Object obj = rc.get(col);
			record.put(column.getName().toLowerCase(),obj);
		}
		record.put("NR",row+1+(start));
		data.put(record);
	}
	myout.put("data",data);
	myout.put("success",true);
}
out.clearBuffer();%><%=myout%>